import Vue from 'vue'
import Router from 'vue-router'
import {ModuleManager} from 'framework/Module'
import Guest from "@/util/accesscontrol/Guest";
import NoAuth from "@/util/accesscontrol/NoAuth"
import DataModel from 'framework/datamodel';
import Api from '@/util/api'
import Session from 'framework/Session'

import environments from '@/util/environments';

Vue.use(Router);
const routerRules = new Router({
  mode: 'history',
  routes: ModuleManager.routes(),
});
routerRules.beforeEach(async (to, from, next) => {
  if (to.meta.hasOwnProperty('accesscontrol') === false) {
    to.meta.accesscontrol = new NoAuth();
  }
  if (Session.has("account")) {
    const account = Session.get("account");
    console.log(account);
    try {
      const responseAccount = await Api.host('base.auth').get('/admins/info');
      let accountInfoModel = DataModel.buildModel(responseAccount.data.type, responseAccount.data);
      let accountModel = accountInfoModel.admin;
      let accountData = {
        ...accountModel,
        token: account.token
      };
      environments.use('account').commit('account', accountData);
    } catch (error) {
      environments.use('account').commit('clear');
      console.log(error);
    }
  }


  return await to.meta.accesscontrol.run(to, from, next);
});
export default routerRules
